package com.srwl.mytx.widget;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.snackbar.Snackbar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.MulctViewAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.LiveRecord;
import com.srwl.mytx.domain.Mulct;
import com.srwl.mytx.domain.MulctItem;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.LiveService;
import com.srwl.mytx.utils.PayUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MulctDialog extends BottomSheetDialog {
    String TAG = MulctDialog.class.getSimpleName();
    private Context context;
    private ViewPager vp;
    private LiveRecord liveRecord;
    private String liveRoomId;
    private int audienceSize;
    private MulctViewAdapter mulctViewAdapter;
    private InteractionListener mListener;
    private List<ImageView> dots; //小圆点2
    private List<MulctItem> presents;


    public MulctDialog(Context context, LiveRecord liveRecord, String liveRoom, int audienceSize, InteractionListener listener, List<MulctItem> presents) {
        super(context, R.style.BottomDialog_v1);
        this.liveRecord = liveRecord;
        this.liveRoomId = liveRoom;
        this.audienceSize = audienceSize;
        setContentView(R.layout.present_dialog);
        this.context = context;
        mListener = listener;
        this.presents = presents;
        setVp(listener, presents);
    }

    public MulctDialog(@NonNull Context context) {
        super(context);
    }

    public void setCurrentItem() {
        vp.setCurrentItem(0);
    }

    public MulctDialog(@NonNull Context context, int theme) {
        super(context, theme);
    }

    protected MulctDialog(@NonNull Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    private void setVp(InteractionListener listener, List<MulctItem> presents) {


      /*  List<RecyclerView> list = new ArrayList<>();
        RecyclerView  mRecyclerView =  new RecyclerView(context);
        mRecyclerView.setLayoutManager(new GridLayoutManager(context,3));
        RecyclerView  mRecyclerView01 =  new RecyclerView(context);
        mRecyclerView01.setLayoutManager(new GridLayoutManager(context,3));

            List<Present> datas  = initData();
            List<Present> datas1  = datas.subList(0,9);
            List<Present> datas2  = datas.subList(9,12);
        PresentRecyclerViewAdapter presentRecyclerViewAdapter = new PresentRecyclerViewAdapter(context,datas1);
        PresentRecyclerViewAdapter presentRecyclerViewAdapter01 = new PresentRecyclerViewAdapter(context,datas2);
        mRecyclerView.setAdapter(presentRecyclerViewAdapter);
        mRecyclerView01.setAdapter(presentRecyclerViewAdapter01);

        list.add(mRecyclerView);
        list.add(mRecyclerView01);


        vp = findViewById(R.id.vp);
        vp.setAdapter(new PresentAdapter(context, list));
*/


        if (presents == null) {
            return;
        }
        int count = presents.size();
        int pageCount;
        int pageSize = 9;
        int m = count % pageSize;
        if (m > 0) {
            pageCount = count / pageSize + 1;
        } else {
            pageCount = count / pageSize;
        }
        List<RecyclerView> list = new ArrayList<>();
        for (int i = 1; i <= pageCount; i++) {

            RecyclerView mRecyclerView = new RecyclerView(context);
            //mRecyclerView.setBackgroundResource(R.drawable.pop_transparent_background);
            mRecyclerView.setLayoutManager(new GridLayoutManager(context, 3));
            if (m == 0) {
                List<MulctItem> datas1 = presents.subList((i - 1) * pageSize, pageSize * (i));
                mulctViewAdapter = new MulctViewAdapter(context, datas1);
                mRecyclerView.setAdapter(mulctViewAdapter);
                list.add(mRecyclerView);
                setOnClick();
            } else {
                if (i == pageCount) {
                    List<MulctItem> datas1 = presents.subList((i - 1) * pageSize, count);
                    mulctViewAdapter = new MulctViewAdapter(context, datas1);
                    mRecyclerView.setAdapter(mulctViewAdapter);
                    list.add(mRecyclerView);
                    setOnClick();

                } else {
                    List<MulctItem> datas1 = presents.subList((i - 1) * pageSize, pageSize * i);
                    mulctViewAdapter = new MulctViewAdapter(context, datas1);
                    mRecyclerView.setAdapter(mulctViewAdapter);
                    list.add(mRecyclerView);
                    setOnClick();
                }
            }


        }


        vp = findViewById(R.id.vp);
        vp.setAdapter(new PresentAdapter(context, list));
        LinearLayout dotLayout = findViewById(R.id.dot);
        dots = new ArrayList<>();
        for (int i = 1; i <= pageCount; i++) {
            ImageView dot = new ImageView(context);
            dot.setImageResource(R.drawable.checked02);
            dot.setMaxWidth(10);
            dot.setMaxHeight(10);
            dots.add(dot);
            dotLayout.addView(dot);
        }
        //将第一个小圆点设为默认选中
        (dots.get(0)).setImageResource(R.drawable.checked01);


        //滑动监听
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
              /*  RadioButton rbtn01 = findViewById(R.id.rbtn01);
                RadioButton rbtn02 = findViewById(R.id.rbtn02);

                switch (i) {
                    case 0:
                        rbtn01.setChecked(true);
                        break;

                    case 1:
                        rbtn02.setChecked(true);
                        break;

                }*/
            }

            @Override
            public void onPageSelected(int pos) {
                for (int i = 0; i < dots.size(); i++) {
                    ImageView dot = dots.get(i);
                    if (pos == i) {

                        dot.setImageResource(R.drawable.checked01);

                    } else {
                        dot.setImageResource(R.drawable.checked02);
                    }
                }


            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });


    }

    private void setOnClick() {
        mulctViewAdapter.setOnItemClickListent(new MulctViewAdapter.OnItemClickListener() {
            @Override
            public void onClick(MulctItem present) {
                double money = present.getAmount();

                double finalMoney = money;

                new PayUtils(money, context, new PayUtils.InteractionListener() {
                    @Override
                    public void onPrepareComplete(String payPassword) {
                        mulct(finalMoney, payPassword);

                    }
                });

            }
        });
    }


    public interface InteractionListener {

        void onMulctSuccess(Mulct mulct, Integer progress);

        void showToast(String message);
    }





/*


        RetrofitManager.getInstance().createRequest(LiveService.class).getAllPresent().enqueue(new Callback<CommonResult>() {
            @Override
            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                CommonResult body = response.body();

                // Log.d("返回的礼物数据:"+ (body.getData()))
                if(!response.isSuccessful()){
                    Log.e(TAG, "onResponse: " + response.message());
                    return;
                }

                JSONArray  jsonArray = (JSONArray) body.getData();
                if(jsonArray == null){
                    return;
                }
                List<Present>  presents = jsonArray.toJavaList(Present.class);
                setVp(mListener,presents);

                Log.d(TAG, "礼物列表" + jsonArray.toJSONString());



            }



            @Override
            public void onFailure(Call<CommonResult> call, Throwable t) {
                Log.e(TAG, "礼物请求失败onFailure: "+ t.getMessage() );
            }
        });


    }
*/


    private void mulct(double money, String payPassword) {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        if (liveRecord == null) {
            return;
        }
        Mulct mulct = new Mulct();
        mulct.setAmount(money);
        mulct.settId(liveRecord.getAnchorId());
        mulct.setrId(liveRecord.getId());
        mulct.setlId(liveRoomId);
        mulct.setAudienceSize(audienceSize);
        Map<String, Object> body = new HashMap();
        body.put("mulct", mulct);
        body.put("payPassword", payPassword);

        RetrofitManager.getInstance().createRequest(LiveService.class)
                .mulct(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "点踩出错:" + response.code());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "点踩出错:" + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.TOKEN_INVALID:
                                    showToast(vp, getContext().getString(R.string.login_expire));
                                    break;
                                case Constant.BALANCE_NOT_ENOUGH:
                                    showToast(vp, getContext().getString(R.string.balance_not_enough_to_recharge));
                                    break;
                                case Constant.GET_LOCK_FAIL://打赏频率过高，并发了，这种可能太小，，
                                    showToast(vp, getContext().getString(R.string.system_busy));
                            }
                            return;
                        }

                        JSONObject data = (JSONObject) result.getData();
                        Integer progress = data.getInteger("progress");
                        double balance = data.getDouble("balance");
                        //myUserInfo.setBalance(balance);
                        UserProfileManager.getInstance().setUserBalance(balance);
                        Log.d(TAG, "点踩完成 余额：" + balance);
                        //notifyMulct(mulct, duration);
                        //点踩的人 ，自己不会受到 点踩后服务端推送到直播间的 点踩信息，需要在点踩成功后的响应里面，调用显示点踩的 动画

                        if (mListener != null) {

                            mListener.onMulctSuccess(mulct, progress);
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }


    /**
     * 检查余额是否足够，
     *
     * @param money
     * @return
     */
    private boolean isBalanceEnough(double money) {
        double balance = UserProfileManager.getInstance().getUserBalance();
        Log.d(TAG, "当前余额：" + balance);
        if (balance < money) {

            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
            dialogBuilder.setTitle("提醒");
            dialogBuilder.setMessage(R.string.balance_not_enough_to_recharge);
            dialogBuilder.setPositiveButton("确定", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // startActivity(new Intent(getContext(), ChangeActivity.class));
                    final RechargeDialogFragment rechargeDialogFragment = RechargeDialogFragment.newInstance();
                    // rechargeDialogFragment.show(getFragmentManager(), "recharge");
                    rechargeDialogFragment.setOnFragmentInteractionListener(new RechargeDialogFragment.OnFragmentInteractionListener() {
                        @Override
                        public void onRechargeSuccess(Double totalBalance) {
                            //对个人余额进行增加操作
                            UserProfileManager.getInstance().setUserBalance(totalBalance);
                            rechargeDialogFragment.dismiss();
                        }

                        @Override
                        public void showToast(String message) {

                        }
                    });
                }
            });
            dialogBuilder.setNegativeButton("取消", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            dialogBuilder.create().show();
            //showToast(getString(R.string.balance_not_enough));
            return false;
        }
        return true;
    }

    private void showToast(View view, String content) {
        Snackbar.make(view, content, Snackbar.LENGTH_LONG).show();
    }


}
